
const nunjucks = require('nunjucks');


let res = {

    // 注册
    "/register": ["get", async (ctx) => {
        ctx.render('register.html', {
            title: "欢迎注册"
        });
    }],

    // 注册提交
    "/doRegister": ["post", async (ctx) => {

        let uName = ctx.request.body.username.trim();
        let pwd = ctx.request.body.password.trim();
        let pwdOk = ctx.request.body.passwordOk.trim();

        //判断密码或账号是否有误
        if (uName !== "" && pwd !== "" && pwd === pwdOk) {

            //引入users.js
            const { objMod } = require('../models');

            //定义objMod下的Users模块
            let users = objMod.Users;

            // 创建该表，这将检查数据库中表的当前状态
            await users.sync({ alter: true })

            try {
                //向表中插入数据
                await users.create({ username: uName, password: pwd });

                // 跳到登录界面
                ctx.redirect("/");


            } catch (error) {

                ctx.body = await nunjucks.renderString(`

                <p>此页面<span id="count-span">5</span>秒后将自动跳转回注册界面</p>

    <script type="text/javascript">

        alert("注册失败,账号可能已经存在");

        window.onload = function () {
            var count = 5;
            setInterval(function () {
                count--;
                if (count == 0) {
                    window.location.href = "/register";//跳转后的页面

                } else {
                    document.getElementById("count-span").innerHTML = count;
                }
            }, 1000);
        }
    </script>
              `);

            }

        } else {

            ctx.body = await nunjucks.renderString(`
            <script type="text/javascript">
            alert("注册失败,请检查账号和密码不能为空或重复密码是否错误");
            window.location.href = "/register";//跳转后的页面
         </script>
           `);
        }
    }]

}


module.exports = res;